"""
自动发布Agent到智能体中心的脚本
包含：创建Agent、获取API密钥、自动审核、完成发布

流程：
1. 创建Agent
2. 获取API密钥和AppID
3. 配置并发布到智能体中心
4. 等待审核完成
5. 验证发布状态
"""

import os
import sys
import time
import json
from pathlib import Path
from typing import Dict, Any, Optional
from dotenv import load_dotenv

# Windows编码修复
if sys.platform == 'win32':
    os.environ['PYTHONIOENCODING'] = 'utf-8'

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

# 加载环境变量
load_dotenv(project_root / '.env')

from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig


class AgentAutoPublisher:
    """Agent自动发布器"""

    def __init__(self, workspace_id: Optional[str] = None):
        """
        初始化发布器

        Args:
            workspace_id: 工作空间ID，默认从配置读取
        """
        self.client = HiAgentAPIClient()
        self.workspace_id = workspace_id or HiAgentConfig.DEFAULT_WORKSPACE_ID
        self.app_id: Optional[str] = None
        self.api_key: Optional[str] = None
        self.api_key_id: Optional[str] = None
        self.publish_id: Optional[str] = None
        self.approval_id: Optional[str] = None  # 审批单ID

    def create_agent(self, agent_config: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建Agent

        Args:
            agent_config: Agent配置信息

        Returns:
            创建结果
        """
        print("[步骤] 步骤1: 创建Agent...")

        # 准备创建请求
        # AppType可选值: Chat, Completion, Workflow, ChatFlow
        app_type_map = {
            "ChatAgent": "Chat",
            "MultiAgent": "ChatFlow",
            "Workflow": "Workflow",
            "Completion": "Completion"
        }
        mode = agent_config.get("mode", "ChatAgent")
        app_type = app_type_map.get(mode, "Chat")

        request_data = {
            "WorkspaceID": self.workspace_id,
            "Name": agent_config.get("name", "自动创建的Agent"),
            "AppType": app_type,
            "Description": agent_config.get("description", "自动创建的Agent"),
            "Icon": agent_config.get("icon", ""),
            "Top": {}  # Top相关参数，前端不需要处理
        }

        # 调用创建API
        result = self.client.make_request(
            action="CreateApp",
            body=request_data
        )

        # 处理不同的响应格式
        if "Response" in result:
            if result.get("Response", {}).get("Error"):
                error = result["Response"]["Error"]
                raise Exception(f"创建Agent失败: {error.get('Code')} - {error.get('Message')}")
            response = result["Response"]
        else:
            # 直接返回格式
            response = result

        self.app_id = response.get("AppID")
        print(f"[成功] Agent创建成功! AppID: {self.app_id}")

        # 立即保存配置草稿
        self._save_config_draft(agent_config)

        return result

    def _save_config_draft(self, agent_config: Dict[str, Any]) -> Dict[str, Any]:
        """
        保存Agent配置草稿

        Args:
            agent_config: Agent配置信息

        Returns:
            保存结果
        """
        print("\n[配置] 保存Agent配置草稿...")

        if not self.app_id:
            raise Exception("请先创建Agent")

        # 构建配置草稿
        app_config_draft = {
            "ModelID": agent_config.get("model_id", "d34idr85oc9ofekvmelg"),
            "ModelConfig": {
                "Temperature": agent_config.get("temperature", 0.7),
                "TopP": agent_config.get("top_p", 0.9),
                "MaxTokens": agent_config.get("max_tokens", 2000),
                "RoundsReserved": agent_config.get("rounds_reserved", 10),
                "RagNum": agent_config.get("rag_num", 5),
                "Strategy": agent_config.get("strategy", "react"),
                "MaxIterations": agent_config.get("max_iterations", 5),
                "RagEnabled": agent_config.get("rag_enabled", False),
                "ReasoningMode": agent_config.get("reasoning_mode", False),
                "ReasoningSwitch": agent_config.get("reasoning_switch", False),
                "ReasoningSwitchType": agent_config.get("reasoning_switch_type", "disabled"),
                "IsAdvancedMode": agent_config.get("is_advanced_mode", False),
                "CurrentTimeEnabled": agent_config.get("current_time_enabled", False),
            },
            "PrePrompt": agent_config.get("prompt", "你是一个AI助手。"),
            "VariableConfigs": agent_config.get("variable_configs", []),
            "ToolIDs": agent_config.get("tool_ids", []),
            "WorkflowIDs": agent_config.get("workflow_ids", []),
            "KnowledgeIDs": agent_config.get("knowledge_ids", []),
        }

        # 如果提供了welcome_message，保存到开场白配置
        if agent_config.get("welcome_message"):
            app_config_draft["OpenMessage"] = agent_config.get("welcome_message")

        request_data = {
            "WorkspaceID": self.workspace_id,
            "AppID": self.app_id,
            "AppConfigDraft": app_config_draft,
            "Top": {}
        }

        result = self.client.make_request(
            action="SaveAppConfigDraft",
            body=request_data
        )

        # 处理响应
        if "Response" in result:
            if result.get("Response", {}).get("Error"):
                error = result["Response"]["Error"]
                raise Exception(f"保存配置草稿失败: {error.get('Code')} - {error.get('Message')}")

        print(f"[成功] 配置草稿保存成功!")
        print(f"   模型ID: {app_config_draft['ModelID']}")
        print(f"   提示词: {app_config_draft['PrePrompt'][:50]}...")

        return result

    def create_api_key(self, name: str = "自动生成的API密钥", expired: str = "forever") -> Dict[str, Any]:
        """
        创建API密钥

        Args:
            name: 密钥名称
            expired: 过期时间 (0.5h, 1h, 6h, 1d, 7d, 15d, 1m, 6m, 1y, forever)

        Returns:
            API密钥信息
        """
        print("\n[密钥] 步骤2: 创建API密钥...")

        if not self.app_id:
            raise Exception("请先创建Agent")

        request_data = {
            "WorkspaceID": self.workspace_id,
            "AppID": self.app_id,
            "Expired": expired,
            "Description": name,
            "ApiKeyType": "api",  # api类型
            "Top": {}  # Top相关参数
        }

        result = self.client.make_request(
            action="CreateAppAPIKey",
            body=request_data
        )

        # 处理不同的响应格式
        if "Response" in result:
            if result.get("Response", {}).get("Error"):
                error = result["Response"]["Error"]
                raise Exception(f"创建API密钥失败: {error.get('Code')} - {error.get('Message')}")
            response = result["Response"]
        else:
            response = result
        self.api_key = response.get("APIKey") or response.get("ApiKey")
        self.api_key_id = response.get("APIKeyID") or response.get("AppKeyID") or response.get("ApiKeyID")

        print(f"[成功] API密钥创建成功!")
        print(f"   APIKeyID: {self.api_key_id}")
        print(f"   APIKey: {self.api_key[:20]}..." if self.api_key else "")

        return result

    def publish_to_center(
        self,
        version: str = "1.0.0",
        version_desc: str = "首次发布",
        category_codes: list = None,
        auth_type: str = "Public",
        auth_range_type: str = "All"
    ) -> Dict[str, Any]:
        """
        发布到智能体中心

        Args:
            version: 版本号
            version_desc: 版本描述
            category_codes: 分类代码列表
            auth_type: 授权类型 (Public/Private)
            auth_range_type: 授权范围 (All/Partial)

        Returns:
            发布结果
        """
        print("\n[发布] 步骤3: 发布到智能体中心...")

        if not self.app_id:
            raise Exception("请先创建Agent")

        # 默认分类
        if category_codes is None:
            category_codes = ["WorkAssistant"]  # 工作助手分类

        # 获取草稿配置
        print("[发布] 获取Agent配置...")
        config_result = self.client.make_request(
            action="GetAppConfigDraft",
            body={
                "WorkspaceID": self.workspace_id,
                "AppID": self.app_id,
                "Top": {}
            }
        )

        # 处理配置响应
        if "Response" in config_result:
            config_draft = config_result["Response"]
        else:
            config_draft = config_result

        # 构建发布请求
        request_data = {
            "WorkspaceID": self.workspace_id,
            "AppID": self.app_id,
            "Version": version,
            "VersionDescription": version_desc,
            "AgentMode": config_draft.get("DraftAgentMode", "Single"),
            "PublishAppCenter": {
                "IsPublish": True,
                "AuthType": auth_type,
                "CategoryCodeList": category_codes,
                "AuthRangeType": auth_range_type
            },
            "Top": {}
        }

        # 根据AgentMode添加配置
        agent_mode = config_draft.get("DraftAgentMode", "Single")
        if agent_mode == "Single":
            app_config = config_draft.get("AppConfigDraft", {})
            if app_config:
                request_data["AppConfig"] = app_config
                print(f"[发布] 添加Single模式配置")
        elif agent_mode == "Multi":
            multi_config = config_draft.get("MultiAgentConfigDraft", {})
            if multi_config:
                request_data["MultiAgentConfigInfo"] = multi_config
                print(f"[发布] 添加Multi模式配置")

        print(f"[发布] AgentMode: {agent_mode}")

        result = self.client.make_request(
            action="PublishApp",
            body=request_data
        )

        # 添加调试输出
        print(f"\n[DEBUG] PublishApp 完整响应:\n{result}\n")

        # 处理不同的响应格式
        if "Response" in result:
            if result.get("Response", {}).get("Error"):
                error = result["Response"]["Error"]
                raise Exception(f"发布失败: {error.get('Code')} - {error.get('Message')}")
            response = result["Response"]
        elif "ResponseMetadata" in result:
            # ResponseMetadata格式
            metadata = result["ResponseMetadata"]
            error = metadata.get("Error", {})

            # ApprovalCreated不是错误，而是正常的审批流程
            if error.get("Code") == "ApprovalCreated":
                # 从响应中提取审批ID
                approval_id = error.get("Message", "").split(": ")[-1]
                # 同时检查Data字段
                if not approval_id or approval_id == error.get("Message"):
                    approval_data = error.get("Data", {})
                    approval_id = approval_data.get("__Message.ApprovalID", approval_id)

                # 保存审批ID到实例变量，供后续auto_approve使用
                self.approval_id = approval_id
                print(f"[信息] 审批单已创建: {approval_id}")
                self.publish_id = None  # 发布还未完成
                print(f"[成功] 发布请求已提交，等待审批!")
                return result
            elif error:
                raise Exception(f"发布失败: {error.get('Code')} - {error.get('Message')}")
            response = result
        else:
            # 直接返回格式
            response = result

        self.publish_id = response.get("PublishID")
        publish_status = response.get("Status")
        app_center_status = response.get("AppCenterStatus", {})

        print(f"[成功] 发布请求已提交!")
        print(f"   PublishID: {self.publish_id}")
        print(f"   状态: {publish_status}")
        print(f"   智能体中心状态: {app_center_status.get('Status')}")

        return result

    def check_publish_status(self) -> Dict[str, Any]:
        """
        检查发布状态

        Returns:
            发布历史信息
        """
        print("\n[状态] 检查发布状态...")

        if not self.app_id:
            raise Exception("请先创建Agent")

        # 构建请求参数
        request_data = {
            "WorkspaceID": self.workspace_id,
            "AppID": self.app_id,
            "Filter": {}
        }

        # 只有在publish_id存在时才添加PublishIDs过滤
        if self.publish_id:
            request_data["Filter"]["PublishIDs"] = [self.publish_id]
            print(f"   使用PublishID过滤: {self.publish_id}")
        else:
            print(f"   查询所有发布记录")

        result = self.client.make_request(
            action="ListAppPublishHistory",
            body=request_data
        )

        # 处理不同的响应格式
        if "Response" in result:
            if result.get("Response", {}).get("Error"):
                error = result["Response"]["Error"]
                raise Exception(f"查询发布状态失败: {error.get('Code')} - {error.get('Message')}")
            items = result["Response"].get("Items", [])
        else:
            items = result.get("Items", [])

        if items:
            latest = items[0]

            # 正确的字段名是 ID，不是 PublishID
            publish_id = latest.get("ID")
            published_channels = latest.get("PublishedChannels", [])
            agent_mode = latest.get("AgentMode", "Unknown")

            # 判断发布状态：如果有发布渠道，说明已发布
            is_published = len(published_channels) > 0
            status = "Success" if is_published else "Pending"

            print(f"\n   PublishID: {publish_id}")
            print(f"   AgentMode: {agent_mode}")
            print(f"   Published Channels: {published_channels}")
            print(f"   Status: {status}")

            # 如果实例还没有publish_id，保存它
            if not self.publish_id and publish_id:
                self.publish_id = publish_id
                print(f"   [INFO] Saved PublishID: {publish_id}")

            # 检查是否发布到智能体中心
            if "AppCenter" in published_channels:
                print(f"   [SUCCESS] Published to AppCenter!")
            elif is_published:
                print(f"   [INFO] Published to: {', '.join(published_channels)}")
            else:
                print(f"   [WARNING] Not yet published to any channel")

            # 显示第三方发布渠道状态
            thirdparty_channels = latest.get("ThirdpartyPublishChannels", [])
            if thirdparty_channels:
                print(f"   Third-party Channels: {len(thirdparty_channels)}")
        else:
            print(f"\n[WARNING] No publish history found for this App")

        return result

    def get_approval_id(self, app_id: str = None) -> Optional[str]:
        """
        获取Agent发布的审批单ID

        Args:
            app_id: Agent ID，默认使用self.app_id

        Returns:
            审批单ID，如果没有找到则返回None
        """
        print("\n[审批] 查找审批单...")

        target_app_id = app_id or self.app_id
        if not target_app_id:
            raise Exception("请先创建或指定Agent")

        # 获取我提交的审批单列表
        request_data = {
            "Filter": {
                "Kind": "AppPublish",  # 智能体发布类型
                "StatusContains": ["InProgress"]  # 进行中的审批
            },
            "Pagination": {
                "PageSize": 50,  # 每页50条
                "PageNum": 1
            },
            "Top": {}
        }

        result = self.client.make_request(
            action="ListCommittedApproval",
            body=request_data
        )

        # 处理不同的响应格式
        if "Response" in result:
            if result.get("Response", {}).get("Error"):
                error = result["Response"]["Error"]
                raise Exception(f"查询审批单失败: {error.get('Code')} - {error.get('Message')}")
            items = result["Response"].get("Items", [])
        else:
            items = result.get("Items", [])

        # 查找匹配的审批单
        for item in items:
            if item.get("TargetID") == target_app_id:
                approval_id = item.get("ID")
                print(f"   找到审批单ID: {approval_id}")
                print(f"   状态: {item.get('Status')}")
                print(f"   创建时间: {item.get('CreatedAt')}")
                return approval_id

        print("   未找到匹配的审批单")
        return None

    def auto_approve(self, approval_id: str = None, message: str = "自动审批通过") -> Dict[str, Any]:
        """
        自动通过审批

        Args:
            approval_id: 审批单ID，如果不传则自动查找
            message: 审批备注

        Returns:
            审批结果
        """
        print("\n[审批] 自动通过审批...")

        # 优先级：传入参数 > 实例变量 > 自动查找
        target_approval_id = approval_id
        if not target_approval_id and hasattr(self, 'approval_id'):
            # 使用publish_to_center保存的审批ID
            target_approval_id = self.approval_id
            print(f"[审批] 使用已保存的审批ID: {target_approval_id}")
        if not target_approval_id:
            # 最后尝试自动查找
            target_approval_id = self.get_approval_id()
            if not target_approval_id:
                raise Exception("未找到待审批的审批单")

        request_data = {
            "ID": target_approval_id,
            "Message": message,
            "Top": {}
        }

        result = self.client.make_request(
            action="ApproveApproval",
            body=request_data
        )
        print(33333, result)
        # 处理响应（可能为空响应表示成功）
        if result is None:
            # 空响应视为成功
            print(f"[成功] 审批操作已提交! ID: {target_approval_id}")
            print(f"[信息] 等待审批流程完成...")
            return {"success": True, "approval_id": target_approval_id}

        if "Response" in result and result.get("Response", {}).get("Error"):
            error = result["Response"]["Error"]
            raise Exception(f"审批失败: {error.get('Code')} - {error.get('Message')}")

        print(f"[成功] 审批操作已提交! ID: {target_approval_id}")
        print(f"[信息] 等待审批流程完成...")

        # 等待几秒钟让审批流程处理
        import time
        time.sleep(3)

        # 检查审批状态
        check_result = self.client.make_request(
            action="ListCommittedApproval",
            body={
                "Filter": {
                    "Kind": "AppPublish",
                    "IDs": [target_approval_id]
                },
                "Pagination": {
                    "PageSize": 10,
                    "PageNum": 1
                },
                "Top": {}
            }
        )

        if "Response" in check_result:
            items = check_result["Response"].get("Items", [])
        else:
            items = check_result.get("Items", [])

        if items:
            status = items[0].get("Status")
            print(f"[状态] 当前审批状态: {status}")
            if status == "Approved":
                print(f"[成功] 审批已完成!")
            elif status == "InProgress":
                print(f"[警告] 审批仍在进行中，可能需要人工介入")

        return result

    def wait_for_approval(self, timeout: int = 300, check_interval: int = 10) -> bool:
        """
        等待审核完成

        Args:
            timeout: 超时时间（秒）
            check_interval: 检查间隔（秒）

        Returns:
            是否审核通过
        """
        print(f"\n[等待] 等待审核完成 (超时: {timeout}秒, 检查间隔: {check_interval}秒)...")

        start_time = time.time()

        while time.time() - start_time < timeout:
            result = self.check_publish_status()

            # 处理不同的响应格式
            if "Response" in result:
                items = result["Response"].get("Items", [])
            else:
                items = result.get("Items", [])

            if items:
                latest = items[0]
                published_channels = latest.get("PublishedChannels", [])

                # 成功状态：已发布到任何渠道
                if len(published_channels) > 0:
                    print(f"[成功] 发布成功! 渠道: {published_channels}")
                    return True

                # 进行中状态：有记录但还未发布
                elapsed = int(time.time() - start_time)
                print(f"   状态: 等待发布中, 已等待{elapsed}秒, 继续等待...")
                time.sleep(check_interval)
                continue
            else:
                print(f"   未找到发布记录，继续等待...")

            time.sleep(check_interval)

        print(f"[警告] 等待超时 ({timeout}秒)")
        return False

    def verify_published_status(self) -> bool:
        """
        验证Agent是否真正发布成功

        Returns:
            是否已发布
        """
        print("\n[验证] 验证Agent发布状态...")

        if not self.app_id:
            raise Exception("请先创建Agent")

        # 获取App信息
        app_info = self.get_published_app_info()

        # 处理响应格式
        if "Response" in app_info:
            app_data = app_info["Response"].get("AppBriefInfo", {})
        else:
            app_data = app_info.get("AppBriefInfo", {})

        is_published = app_data.get("IsPublished", False)
        is_published_center = app_data.get("IsPublishedAppCenter", False)
        published_channels = app_data.get("PublishedChannels", [])

        print(f"   IsPublished (是否已发布): {is_published}")
        print(f"   IsPublishedAppCenter (智能体中心): {is_published_center}")
        print(f"   PublishedChannels (发布渠道): {published_channels}")

        # 检查发布历史
        history = self.check_publish_status()
        if "Response" in history:
            items = history["Response"].get("Items", [])
        else:
            items = history.get("Items", [])

        if items:
            latest = items[0]
            history_channels = latest.get("PublishedChannels", [])
            print(f"   发布历史中的渠道: {history_channels}")

            # 检查是否发布到智能体中心
            if "AppCenter" in history_channels:
                print(f"   [SUCCESS] 已发布到智能体中心!")

        return is_published or is_published_center or "AppCenter" in published_channels

    def get_published_app_info(self) -> Dict[str, Any]:
        """
        获取已发布的App信息

        Returns:
            App详细信息
        """
        print("\n[信息] 获取已发布的App信息...")

        if not self.app_id:
            raise Exception("请先创建Agent")

        request_data = {
            "WorkspaceID": self.workspace_id,
            "AppID": self.app_id
        }

        result = self.client.make_request(
            action="GetAppBrief",
            body=request_data
        )

        # 处理不同的响应格式
        if "Response" in result:
            if result.get("Response", {}).get("Error"):
                error = result["Response"]["Error"]
                raise Exception(f"获取App信息失败: {error.get('Code')} - {error.get('Message')}")
            app_info = result["Response"]
        else:
            app_info = result.get("AppBriefInfo", result)

        print(f"   名称: {app_info.get('AppName', app_info.get('Name', 'N/A'))}")
        print(f"   是否已发布: {app_info.get('IsPublished', False)}")
        print(f"   已发布渠道: {app_info.get('PublishedChannels', [])}")

        return result

    def enable_api_access(self, enable: bool = True) -> Dict[str, Any]:
        """
        开启或关闭API访问

        Args:
            enable: True为开启，False为关闭

        Returns:
            操作结果
        """
        action_text = "开启" if enable else "关闭"
        print(f"\n[API] {action_text}API访问...")

        if not self.app_id:
            raise Exception("请先创建Agent")

        request_data = {
            "WorkspaceID": self.workspace_id,
            "AppID": self.app_id,
            "Enable": enable,
            "Top": {}
        }

        result = self.client.make_request(
            action="UpdateAppAPIRunnable",
            body=request_data
        )

        if result.get("Response", {}).get("Error"):
            error = result["Response"]["Error"]
            raise Exception(f"{action_text}API访问失败: {error.get('Code')} - {error.get('Message')}")

        print(f"[成功] API访问已{action_text}!")

        return result

    def auto_publish(
        self,
        agent_config: Dict[str, Any],
        version: str = "1.0.0",
        auto_approve: bool = False,
        wait_approval: bool = False,
        approval_timeout: int = 300
    ) -> Dict[str, Any]:
        """
        完整的自动发布流程

        Args:
            agent_config: Agent配置
            version: 版本号
            auto_approve: 是否自动审批（优先级高于wait_approval）
            wait_approval: 是否等待审核
            approval_timeout: 审核超时时间

        Returns:
            发布结果摘要
        """
        print("=" * 60)
        print("[Agent] 开始自动发布Agent流程")
        print("=" * 60)

        try:
            # 1. 创建Agent
            create_result = self.create_agent(agent_config)

            # 2. 创建API密钥
            key_result = self.create_api_key()

            # 3. 发布到智能体中心
            publish_result = self.publish_to_center(
                version=version,
                version_desc=agent_config.get("version_desc", "首次发布"),
                category_codes=agent_config.get("category_codes"),
                auth_type=agent_config.get("auth_type", "Public"),
                auth_range_type=agent_config.get("auth_range_type", "All")
            )

            # 4. 审批处理
            approval_success = False
            if auto_approve:
                # 自动审批模式
                try:
                    # 稍等一下让审批单创建完成
                    time.sleep(2)
                    self.auto_approve()
                    approval_success = True

                    # 审批通过后，等待发布流程完成
                    if wait_approval:
                        print("\n[等待] 审批已通过，等待发布流程完成...")
                        approval_success = self.wait_for_approval(timeout=approval_timeout)
                except Exception as e:
                    print(f"[警告] 自动审批失败: {str(e)}")
                    print("       将等待手动审批或自动通过")
                    if wait_approval:
                        approval_success = self.wait_for_approval(timeout=approval_timeout)
            elif wait_approval:
                # 等待审批模式
                approval_success = self.wait_for_approval(timeout=approval_timeout)

            # 5. 开启API访问
            api_enabled = False
            try:
                self.enable_api_access(enable=True)
                api_enabled = True
            except Exception as api_error:
                print(f"[警告] 开启API访问失败: {str(api_error)}")
                print("       您可能需要手动在平台上开启API访问")

            # 6. 验证发布状态
            publish_verified = False
            try:
                publish_verified = self.verify_published_status()
            except Exception as verify_error:
                print(f"[警告] 验证发布状态失败: {str(verify_error)}")

            # 7. 获取最终信息
            app_info = self.get_published_app_info()

            # 处理app_info的响应格式
            if "Response" in app_info:
                app_info_data = app_info["Response"]
            else:
                app_info_data = app_info

            # 汇总结果
            summary = {
                "success": approval_success if wait_approval else True,
                "app_id": self.app_id,
                "api_key": self.api_key,
                "api_key_id": self.api_key_id,
                "publish_id": self.publish_id,
                "api_enabled": api_enabled,
                "publish_verified": publish_verified,
                "app_info": app_info_data
            }

            print("\n" + "=" * 60)
            print("[状态] 发布结果摘要:")
            print("=" * 60)
            print(f"AppID: {self.app_id}")
            print(f"API Key: {self.api_key}")
            print(f"API Key ID: {self.api_key_id}")
            print(f"Publish ID: {self.publish_id}")
            print(f"审核状态: {'[成功] 通过' if approval_success else '[失败] 未通过或超时'}")
            print(f"API访问: {'[成功] 已开启' if api_enabled else '[失败] 未开启'}")
            print(f"发布验证: {'[成功] 已发布' if publish_verified else '[警告] 未发布或审核中'}")
            print("=" * 60)

            return summary

        except Exception as e:
            print(f"\n[失败] 发布过程出错: {str(e)}")
            raise


def main():
    """主函数 - 示例用法"""

    # Agent配置示例
    agent_config = {
        "name": "测试Agent-自动发布",
        "description": "这是一个通过自动化脚本发布的测试Agent",
        "mode": "ChatAgent",  # ChatAgent 或 MultiAgent
        "model_id": "ep-20241231203825-nwz4f",  # 替换为实际的模型ID
        "prompt": "你是一个友好的AI助手，帮助用户解答问题。",
        "welcome_message": "你好！我是自动发布的测试Agent，有什么可以帮助你的吗？",
        "icon": "",  # 可选的图标URL

        # 发布配置
        "version_desc": "通过自动化脚本首次发布",
        "category_codes": ["WorkAssistant"],  # 分类代码（可选: BusinessAssistant, Education, Finance等）
        "auth_type": "Public",  # Public 或 Private
        "auth_range_type": "All"  # All 或 Partial
    }

    # 创建发布器
    publisher = AgentAutoPublisher()

    # 执行自动发布
    try:
        result = publisher.auto_publish(
            agent_config=agent_config,
            version="1.0.0",
            auto_approve=True,  # 自动审批（推荐）
            wait_approval=False,  # 如果自动审批失败，是否等待审核
            approval_timeout=300  # 审核超时时间（秒）
        )

        # 保存结果到文件
        output_file = project_root / "scripts" / "publish_result.json"
        with open(output_file, "w", encoding="utf-8") as f:
            json.dump(result, f, ensure_ascii=False, indent=2)

        print(f"\n[保存] 结果已保存到: {output_file}")

        return result

    except Exception as e:
        print(f"\n[失败] 执行失败: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()
